package basic

import (
	"fmt"
	"strconv"
	"github.com/jinzhu/gorm"
	_ "github.com/go-sql-driver/mysql"
)

/**
连接数据库, 返回gorm.DB连接,read连接
@return sql.DB
 */
func Read() *gorm.DB {
	//root:root@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		Config.Database.Read.User,
		Config.Database.Read.Password,
		Config.Database.Read.Host,
		strconv.Itoa(Config.Database.Read.Port),
		Config.Database.Read.DbName,
	)
	db, err := gorm.Open("mysql", dsn)
	if err != nil {
		logger := Logger{}
		logger.WriteMsg("error", "Read:failed to connect database")
		panic("failed to connect database")
	}
	return db
}

/**
连接数据库, 返回gorm.DB连接, write连接
@return sql.DB
 */
func Write() *gorm.DB  {
	//root:root@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		Config.Database.Write.User,
		Config.Database.Write.Password,
		Config.Database.Write.Host,
		strconv.Itoa(Config.Database.Write.Port),
		Config.Database.Write.DbName,
	)
	db, err := gorm.Open("mysql", dsn)
	if err != nil {
		logger := Logger{}
		logger.WriteMsg("error", "Write:failed to connect database")
		panic("failed to connect database")
	}
	return db
}